package io.renren.modules.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.ConvertUtils;
import io.renren.modules.order.dao.OrderPaymentDao;
import io.renren.modules.order.dto.FileInfoDTO;
import io.renren.modules.order.dto.OrderPaymentDTO;
import io.renren.modules.order.entity.OrderPaymentEntity;
import io.renren.modules.order.service.OrderPaymentService;
import cn.hutool.core.util.StrUtil;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.sys.dto.SysUserDTO;
import io.renren.modules.sys.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单费用表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2024-12-07
 */
@Slf4j
@Service
public class OrderPaymentServiceImpl extends CrudServiceImpl<OrderPaymentDao, OrderPaymentEntity, OrderPaymentDTO> implements OrderPaymentService {

    @Autowired
    private SysUserService sysUserService;

    @Override
    public QueryWrapper<OrderPaymentEntity> getWrapper(Map<String, Object> params){
        String id = (String)params.get("id");

        QueryWrapper<OrderPaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public void deleteByOrderId(Long orderId) {
        log.info("根据订单ID删除订单费用表");
        QueryWrapper<OrderPaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        this.baseDao.delete(wrapper);
    }

    @Override
    public List<OrderPaymentDTO> getOrderPaymentList(List<Long> orderIdList) {
        log.info("根据订单ID集合查询订单费用表");
        if (CollectionUtils.isEmpty(orderIdList)) {
            return Collections.EMPTY_LIST;
        }
        QueryWrapper<OrderPaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.in("order_id", orderIdList);
        List<OrderPaymentEntity> entityList = this.baseDao.selectList(wrapper);
        return ConvertUtils.sourceToTarget(entityList, OrderPaymentDTO.class);
    }

    @Override
    public List<OrderPaymentDTO> getAllOrderPaymentList(Map<String, Object> params) {
        String startDate = (String) params.get("startDate");
        String endDate = (String) params.get("endDate");
        QueryWrapper<OrderPaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.select("id", "order_id", "pay_amount", "is_received", "is_examine", "creator");
        if (StringUtils.isNotEmpty(startDate) && StringUtils.isNotEmpty(endDate)) {
            wrapper.between("pay_date", startDate, endDate);
        }
        List<OrderPaymentEntity> entityList = this.baseDao.selectList(wrapper);
        return ConvertUtils.sourceToTarget(entityList, OrderPaymentDTO.class);
    }

    @Override
    public List<OrderPaymentDTO> listByOrderId(Long orderId) {
        log.info("根据订单ID查询付款记录");
        QueryWrapper<OrderPaymentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", orderId);
        wrapper.orderByDesc("pay_date");
        List<OrderPaymentEntity> entityList = this.baseDao.selectList(wrapper);
        List<OrderPaymentDTO> orderPaymentDtoList = ConvertUtils.sourceToTarget(entityList, OrderPaymentDTO.class);
        // 获取所有的用户信息
        List<SysUserDTO> userDtoList = sysUserService.getAll();
        orderPaymentDtoList.forEach(e -> {
            if (e.getProcessReceivedUserId() != null) {
                SysUserDTO creatorDto = userDtoList.stream().filter(user -> user.getId().compareTo(e.getProcessReceivedUserId()) == 0).findFirst().orElse(null);
                e.setProcessReceivedUserName(creatorDto == null ? "" : creatorDto.getRealName());
            }
            if (StringUtils.isNotEmpty(e.getImagePath())) {
                e.setImageDataList(JSON.parseArray(e.getImagePath(), FileInfoDTO.class));
                e.setImageDataUrlList(e.getImageDataList().stream().map(FileInfoDTO::getUrl).distinct().collect(Collectors.toList()));
            }
        });
        return orderPaymentDtoList;
    }

    @Override
    public void saveOrderPayment(OrderPaymentDTO dto) {
        log.info("保存付款记录");
        if (CollectionUtils.isNotEmpty(dto.getImageDataList())) {
            dto.setImagePath(JSONArray.toJSONString(dto.getImageDataList()));
        }
        this.save(dto);
    }

    @Override
    public void examineOrderPay(OrderPaymentDTO dto) {
        log.info("审核付款");
        // 获取当前的用户信息
        Long userId = SecurityUser.getUserId();
        dto.setProcessReceivedUserId(userId);
        this.update(dto);
    }

}